import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/get_all_goods_list.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/ui/cashier/provider/goods_select_provider.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/cart_item_quantity_picker.dart';
import 'package:get/get.dart';


class GoodsSelectionDialog extends StatelessWidget {
  const GoodsSelectionDialog({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    final mProvider = Get.find<GoodsSelectProvider>();
    final mCashierProvider = Get.find<CashierPageProvider>();

    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    final maxWidth = screenWidth * 0.7; // 设置最大宽度为屏幕宽度的70%
    final maxHeight = screenHeight * 0.7; // 设置最大高度为屏幕高度的80%

    return Material(
      color: Colors.black.withOpacity(0.1),
      child: Center(
        child: Container(
          width: maxWidth,
          height: maxHeight,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6),
          ),
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              // 左侧分类列表
              Obx(() => SizedBox(
                    width: 90,
                    child: ListView.separated(
                      itemCount: mProvider.categoryList.length,
                      separatorBuilder: (context, index) => const SizedBox(height: 8),
                      itemBuilder: (context, index) {
                        final category = mProvider.categoryList[index];
                        return CategoryItem(
                          category: category,
                          onTap: () {
                            mProvider.switchCategory(category);
                            Toast.show(category.name);
                          }, // 实现分类切换逻辑
                        );
                      },
                    ),
                  )),

              //间隔
              const SizedBox(width: 5),

              // 中间商品列表
              Obx(() => Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                          child: GridView.builder(
                            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                              maxCrossAxisExtent: 120,
                              // 主轴间距
                              mainAxisSpacing: 10,
                              // 交叉轴间距
                              crossAxisSpacing: 10,
                              // 子视图宽高比
                              childAspectRatio: 1.0,
                            ),
                            itemCount: mProvider.currentGoodsList.length,
                            itemBuilder: (context, index) {
                              final goods = mProvider.currentGoodsList[index];
                              return GoodsItem(
                                goods: goods,
                              );
                            },
                          ),
                        ),
                        const SizedBox(height: 8),
                        // 底部按钮
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ElevatedButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: const Text('取 消'),
                            ),
                            const SizedBox(width: 15),
                            ElevatedButton(
                              onPressed: () {
                                final goods = mProvider.confirmSelect();
                                mCashierProvider.selectGoods(goods);
                                Navigator.of(context).pop();
                              },
                              child: const Text('确 认'),
                            ),
                          ],
                        ),
                      ],
                    ),
                  )),

              //间隔
              const SizedBox(width: 5),

              // 右侧已选商品
              SizedBox(
                width: 150,
                child: Column(
                  children: [
                    const Text(
                      '已选商品',
                      style: TextStyle(
                        fontSize: Dimens.font_sp18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Obx(() => Expanded(
                          child: ListView.builder(
                            itemCount: mProvider.selectedGoods.length,
                            itemBuilder: (context, index) {
                              final goods = mProvider.selectedGoods[index];
                              return SelectedGoodsItem(
                                key: Key(goods.goodsId),
                                goods: goods,
                              );
                            },
                          ),
                        )),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Category {
  Category({
    required this.id,
    required this.name,
  });

  String id = '';
  String name = '';
}

// 分类项组件
class CategoryItem extends StatelessWidget {
  const CategoryItem({
    Key? key,
    required this.category,
    required this.onTap,
  }) : super(key: key);
  final Category category;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final mProvider = Get.find<GoodsSelectProvider>();
    return InkWell(
      onTap: onTap,
      child: Obx(() => Container(
            padding: const EdgeInsets.symmetric(vertical: 8),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: mProvider.selectCategory?.id == category.id ? Colors.blue : Colours.greyF2F4F8,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Text(
              category.name,
              style: TextStyle(
                color: mProvider.selectCategory?.id == category.id ? Colors.white : Colors.black,
              ),
            ),
          )),
    );
  }
}

// 商品项组件
class GoodsItem extends StatefulWidget {
  const GoodsItem({
    Key? key,
    required this.goods,
  }) : super(key: key);
  final GetAllGoodsList goods;

  @override
  State<GoodsItem> createState() => _GoodsItemState();
}

class _GoodsItemState extends State<GoodsItem> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    final mProvider = Get.find<GoodsSelectProvider>();
    return Card(
      elevation: _isHovered ? 8.0 : 2.0, // 悬浮时增加阴影
      color: Colours.greyF2F4F8,
      child: MouseRegion(
        onEnter: (_) => setState(() => _isHovered = true),
        onExit: (_) => setState(() => _isHovered = false),
        child: InkWell(
          onTap: () => mProvider.selectGoods(widget.goods),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.network(
                widget.goods.coverImageUrl,
                width: 50,
                height: 50,
                fit: BoxFit.cover,
              ),
              Text(
                widget.goods.goodsName,
                overflow: TextOverflow.ellipsis,
              ),
              Text('¥${widget.goods.price.formatYuan}'),
            ],
          ),
        ),
      ),
    );
  }
}

// 已选商品项组件
class SelectedGoodsItem extends StatelessWidget {
  const SelectedGoodsItem({
    super.key,
    required this.goods,
  });

  final GetAllGoodsList goods;

  @override
  Widget build(BuildContext context) {
    final mProvider = Get.find<GoodsSelectProvider>();
    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(3),
      ),
      child: Padding(
        padding: const EdgeInsets.all(6),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 前两个垂直排列的Text
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  goods.goodsName,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: const TextStyle(
                    fontSize: Dimens.font_sp16,
                    // fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 3),
                CartItemQuantityPicker(
                  initialQuantity: goods.count.value,
                  onQuantityChanged: (newQuantity) {
                    goods.count.value = newQuantity;
                    // 在这里更新状态或发送请求
                  },
                ),
              ],
            )),
            // 第三个固定宽度的Text
            Container(
              // color: Colors.yellow, // 设置背景色，方便查看布局空间
              constraints: const BoxConstraints(
                minWidth: 30, // 设置最小宽度
                minHeight: 30, // 设置最小高度
              ),
              child: InkWell(
                onTap: () {
                  mProvider.removeGoods(goods);
                },
                // 圆角
                child: Center(
                  child: Icon(
                    Icons.delete,
                    color: Colors.grey,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
